<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="65%"
    class="agreement-dialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    :modal-class="'agreement-modal'"
  >
    <template #header>
      <!-- 顶部导航 -->
      <div
        class="dialog-header flex items-center justify-between pb-4 border-b border-gray-200 dark:border-gray-700"
      >
        <div class="flex items-center space-x-4">
          <div class="icon-wrapper">
            <i
              class="fas fa-file-contract text-blue-600 dark:text-blue-400"
            ></i>
          </div>
          <div>
            <h2 class="text-xl font-semibold text-gray-900 dark:text-white">
              {{ title }}
            </h2>
            <p class="text-sm text-gray-500 dark:text-gray-400">
              最后更新日期：2024年3月1日
            </p>
          </div>
        </div>
        <div class="flex items-center space-x-2 desktop-only">
          <el-tooltip content="放大文字" placement="top">
            <el-button circle @click="increaseFontSize">
              <i class="fas fa-search-plus"></i>
            </el-button>
          </el-tooltip>
          <el-tooltip content="缩小文字" placement="top">
            <el-button circle @click="decreaseFontSize">
              <i class="fas fa-search-minus"></i>
            </el-button>
          </el-tooltip>
        </div>
      </div>
    </template>

    <div class="agreement-wrapper">
      <div class="flex">
        <!-- 左侧目录导航 - 仅桌面端显示 -->
        <div
          class="agreement-nav w-64 flex-shrink-0 p-4 border-r border-gray-200 dark:border-gray-700 desktop-only"
        >
          <h3 class="text-lg font-semibold mb-3">协议目录</h3>
          <ul class="space-y-2">
            <li
              v-for="(section, index) in currentAgreement.sections"
              :key="index"
              class="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 cursor-pointer"
              :class="{
                'text-primary-600 font-medium': currentSection === section.id,
              }"
              @click="scrollToSection(section.id)"
            >
              {{ section.title }}
            </li>
          </ul>
        </div>

        <!-- 右侧协议内容 -->
        <div
          class="agreement-content flex-1 prose dark:prose-invert max-w-none"
          :style="{ fontSize: fontSize + 'px' }"
          @scroll="handleScroll"
        >
          <template
            v-for="(section, index) in currentAgreement.sections"
            :key="index"
          >
            <div :id="section.id" class="scroll-mt-4">
              <h3 class="text-xl font-semibold mt-6 mb-4">
                {{ section.title }}
              </h3>
              <div
                v-for="(content, cIndex) in section.content"
                :key="cIndex"
                class="mb-4"
              >
                <p
                  v-if="typeof content === 'string'"
                  class="text-gray-700 dark:text-gray-300"
                >
                  {{ content }}
                </p>
                <ul
                  v-else-if="Array.isArray(content)"
                  class="list-disc pl-6 space-y-2"
                >
                  <li
                    v-for="(item, iIndex) in content"
                    :key="iIndex"
                    class="text-gray-700 dark:text-gray-300"
                  >
                    {{ item }}
                  </li>
                </ul>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer flex items-center justify-between">
        <div class="flex items-center">
          <el-checkbox v-model="hasRead" class="text-sm">
            我已阅读并理解以上全部内容
          </el-checkbox>
          <el-tooltip
            content="请先阅读完整协议内容"
            placement="top"
            v-if="!canAgree && !isMobile"
          >
            <i class="fas fa-info-circle ml-2 text-gray-400"></i>
          </el-tooltip>
        </div>
        <div class="flex space-x-4">
          <el-button @click="handleClose" :disabled="loading"
            >暂不同意</el-button
          >
          <el-button
            type="primary"
            @click="handleAgree"
            :loading="loading"
            :disabled="!canAgree && !isMobile"
          >
            同意并继续
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";

const props = defineProps({
  modelValue: Boolean,
  type: {
    type: String,
    default: "platform", // 'platform' 或 'service'
  },
});

const emit = defineEmits(["update:modelValue", "agree"]);

// 对话框状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});

// 标题计算
const title = computed(() => {
  switch (props.type) {
    case "platform":
      return "平台入驻协议";
    case "service":
      return "商家服务协议";
    case "user-service":
      return "用户服务协议";
    case "privacy":
      return "隐私政策";
    default:
      return "用户服务协议";
  }
});

// 协议内容
const platformAgreement = {
  sections: [
    {
      id: "general",
      title: "一、总则",
      content: [
        '1.1 本协议是贵港文化旅游平台（以下简称"平台"）与商家之间就商家入驻等相关事项所订立的契约。',
        "1.2 商家通过网络页面点击确认或以其他方式选择接受本协议，即表示商家同意接受本协议的全部内容。",
        [
          "本协议包含以下重要内容：",
          "平台服务内容及规则",
          "商家权利与义务",
          "平台权利与义务",
          "协议的变更与终止",
        ],
      ],
    },
    {
      id: "qualification",
      title: "二、入驻条件",
      content: [
        "2.1 商家应具备合法的经营资质，包括但不限于：",
        [
          "有效的营业执照",
          "相关行业许可证",
          "法定代表人身份证明",
          "商标注册证（如有）",
        ],
        "2.2 商家应遵守国家相关法律法规及平台规则。",
        "2.3 商家应具备独立承担民事责任的能力。",
      ],
    },
    {
      id: "service",
      title: "三、平台服务",
      content: [
        "3.1 平台为商家提供以下服务：",
        [
          "网络交易平台服务",
          "商家展示推广服务",
          "交易管理服务",
          "资金结算服务",
        ],
        "3.2 平台为商家提供必要的技术支持和培训服务。",
        "3.3 平台提供客户服务支持系统。",
      ],
    },
    {
      id: "obligation",
      title: "四、商家义务",
      content: [
        "4.1 保证提供的所有资料真实、有效、合法。",
        "4.2 遵守平台运营规则，维护平台良好秩序。",
        "4.3 及时处理客户投诉及售后问题。",
        "4.4 保护用户隐私和数据安全。",
      ],
    },
    {
      id: "fee",
      title: "五、费用规则",
      content: [
        "5.1 平台收取的费用包括：",
        ["平台保证金", "技术服务费", "营销推广费（可选）", "其他约定费用"],
        "5.2 具体收费标准以平台公示为准。",
        "5.3 费用结算周期为每月一次。",
      ],
    },
    {
      id: "breach",
      title: "六、违约责任",
      content: [
        "6.1 商家违反本协议约定，平台有权：",
        ["要求商家限期整改", "暂停或终止服务", "扣除保证金", "要求赔偿损失"],
        "6.2 因违约造成损失的，违约方应承担赔偿责任。",
        "6.3 平台保留追究商家法律责任的权利。",
      ],
    },
  ],
};

const serviceAgreement = {
  sections: [
    {
      id: "service-content",
      title: "一、服务内容",
      content: [
        "1.1 平台为商家提供以下服务：",
        ["线上展示服务", "交易管理服务", "推广营销服务", "数据分析服务"],
        "1.2 平台提供商家运营所需的技术支持。",
        "1.3 平台提供运营培训和指导。",
      ],
    },
    {
      id: "service-rules",
      title: "二、服务规则",
      content: [
        "2.1 商家应遵守平台制定的各项服务规则。",
        "2.2 平台有权根据运营需要调整服务规则。",
        "2.3 规则调整将提前通知商家。",
      ],
    },
    {
      id: "product-management",
      title: "三、商品管理",
      content: [
        "3.1 商品信息管理要求：",
        ["信息真实准确", "图片清晰规范", "价格合理公允", "库存及时更新"],
        "3.2 商家应遵守商品上架相关规定。",
        "3.3 违规商品将被强制下架。",
      ],
    },
    {
      id: "transaction-rules",
      title: "四、交易规则",
      content: [
        "4.1 商家应按照平台规定进行交易。",
        "4.2 商家应及时处理订单及客户服务。",
        "4.3 保证交易安全和用户体验。",
      ],
    },
    {
      id: "credit-management",
      title: "五、信用管理",
      content: [
        "5.1 平台建立商家信用评价体系。",
        "5.2 商家应维护良好的信用记录。",
        "5.3 信用评级将影响商家权益。",
      ],
    },
    {
      id: "dispute-resolution",
      title: "六、争议解决",
      content: [
        "6.1 平台提供争议调解服务。",
        "6.2 商家应积极配合争议处理。",
        "6.3 严重争议可能影响商家资格。",
      ],
    },
  ],
};

// 添加用户服务条款
const userServiceAgreement = {
  sections: [
    {
      id: "general",
      title: "一、总则",
      content: [
        '1.1 欢迎您使用贵港文旅+平台（以下简称"平台"）提供的服务。',
        "1.2 本协议是您与平台之间关于使用平台服务所订立的协议。",
        [
          "本协议包含以下重要内容：",
          "用户注册与账户安全",
          "平台服务内容",
          "用户权利与义务",
          "隐私保护",
          "知识产权保护",
        ],
      ],
    },
    {
      id: "registration",
      title: "二、用户注册与账户安全",
      content: [
        "2.1 用户资格",
        [
          "您确认，在您开始注册使用本平台前，您已经具备中华人民共和国法律规定的与您行为相适应的民事行为能力",
          "若您不具备前述与您行为相适应的民事行为能力，请您立即停止注册或使用本平台服务",
        ],
        "2.2 注册信息",
        [
          "您应当提供真实、准确、完整的注册信息",
          "若您提供的注册信息不合法、不真实、不准确、不详尽的，您需要承担因此引起的相应责任及后果",
        ],
        "2.3 账户安全",
        [
          "您应当妥善保管您的账号和密码",
          "您同意在任何情况下不向他人透露账号和密码",
          "任何利用您的账号和密码所进行的活动都将被视为您的行为",
        ],
      ],
    },
    {
      id: "service",
      title: "三、平台服务内容",
      content: [
        "3.1 基础服务",
        [
          "文旅信息浏览与查询",
          "景点门票预订",
          "酒店住宿预订",
          "特色美食推荐",
          "文化活动参与",
        ],
        "3.2 增值服务",
        ["个性化推荐服务", "旅游路线规划", "专业导游预约", "文旅商品购买"],
      ],
    },
    {
      id: "rights",
      title: "四、用户权利与义务",
      content: [
        "4.1 用户权利",
        [
          "享受平台提供的各项服务",
          "对平台服务提出意见和建议",
          "参与平台组织的各项活动",
          "法律法规规定的其他权利",
        ],
        "4.2 用户义务",
        [
          "遵守中华人民共和国相关法律法规",
          "遵守平台的各项规则和要求",
          "不得利用平台从事违法违规活动",
          "不得干扰平台的正常运营",
          "保护自己的账户安全",
        ],
      ],
    },
    {
      id: "liability",
      title: "五、免责与责任限制",
      content: [
        "5.1 平台免责情形",
        [
          "因不可抗力导致的服务中断或故障",
          "因用户原因导致的任何损失",
          "第三方造成的损失",
          "平台正常维护或升级导致的暂时性服务中断",
        ],
        "5.2 服务中断通知",
        "平台将尽可能事先通知用户系统维护、升级或其他原因导致的服务中断或故障",
        "5.3 责任限制",
        "在法律允许的范围内，平台对用户使用服务过程中的损失承担有限责任",
      ],
    },
  ],
};

// 添加隐私政策
const privacyAgreement = {
  sections: [
    {
      id: "collection",
      title: "一、信息收集",
      content: [
        "1.1 我们收集的信息",
        [
          "您提供的个人信息（如姓名、手机号、邮箱等）",
          "您使用服务时产生的信息（如浏览记录、搜索记录等）",
          "设备信息（如设备型号、操作系统、唯一设备标识符等）",
          "位置信息（如GPS信息、WLAN接入点等）",
        ],
        "1.2 信息收集方式",
        ["您主动提供", "自动采集", "第三方合作伙伴分享"],
      ],
    },
    {
      id: "usage",
      title: "二、信息使用",
      content: [
        "2.1 信息使用目的",
        ["提供和改进服务", "个性化推荐", "安全防护", "客户服务"],
        "2.2 信息使用规则",
        [
          "严格遵守相关法律法规",
          "仅在必要的范围内使用信息",
          "采取严格的数据保护措施",
        ],
      ],
    },
    {
      id: "protection",
      title: "三、信息保护",
      content: [
        "3.1 安全措施",
        ["数据加密存储", "访问控制机制", "安全审计机制", "应急响应机制"],
        "3.2 保护期限",
        "我们将在法律要求或业务需要的期限内保留您的个人信息",
        "3.3 未成年人保护",
        "我们非常重视对未成年人个人信息的保护，若您是未成年人，请在监护人指导下使用我们的服务",
      ],
    },
    {
      id: "sharing",
      title: "四、信息共享",
      content: [
        "4.1 信息共享原则",
        ["必要性原则", "安全性原则", "合法性原则"],
        "4.2 信息共享情形",
        [
          "获得您的明确同意",
          "法律法规要求",
          "维护公共安全",
          "保护平台及用户的合法权益",
        ],
      ],
    },
    {
      id: "rights",
      title: "五、您的权利",
      content: [
        "5.1 您可以行使以下权利：",
        [
          "访问、更正您的个人信息",
          "删除您的个人信息",
          "撤回同意授权",
          "注销账号",
          "投诉举报",
        ],
        "5.2 行使权利的方式",
        "您可以通过平台提供的功能或联系客服行使上述权利",
      ],
    },
  ],
};

// 当前协议内容
const currentAgreement = computed(() => {
  switch (props.type) {
    case "platform":
      return platformAgreement;
    case "service":
      return serviceAgreement;
    case "user-service":
      return userServiceAgreement;
    case "privacy":
      return privacyAgreement;
    default:
      return userServiceAgreement;
  }
});

// 状态控制
const loading = ref(false);
const hasRead = ref(false);
const fontSize = ref(14);
const scrollPosition = ref(0);
const currentSection = ref("");

// 添加移动端检测
const isMobile = computed(() => {
  return window.innerWidth <= 768;
});

// 修改可同意条件判断
const canAgree = computed(() => {
  if (isMobile.value) {
    return hasRead.value; // 移动端只需要勾选复选框
  }
  return hasRead.value && scrollPosition.value > 0.8; // 桌面端需要滚动到底部
});

// 字体大小调整
const increaseFontSize = () => {
  if (fontSize.value < 18) {
    fontSize.value += 1;
  }
};

const decreaseFontSize = () => {
  if (fontSize.value > 12) {
    fontSize.value -= 1;
  }
};

// 滚动到指定章节
const scrollToSection = (sectionId) => {
  const element = document.getElementById(sectionId);
  if (element) {
    element.scrollIntoView({ behavior: "smooth" });
    currentSection.value = sectionId;
  }
};

// 监听滚动位置
const handleScroll = (e) => {
  const container = e.target;
  const scrollPercentage =
    container.scrollTop / (container.scrollHeight - container.clientHeight);
  scrollPosition.value = scrollPercentage;
};

// 关闭对话框
const handleClose = () => {
  ElMessage.info("您已取消同意协议");
  dialogVisible.value = false;
};

// 同意协议
const handleAgree = async () => {
  if (!canAgree.value) {
    ElMessage.warning("请先阅读完整协议内容");
    return;
  }

  loading.value = true;
  try {
    await new Promise((resolve) => setTimeout(resolve, 500)); // 模拟请求
    emit("agree");
    dialogVisible.value = false;
    ElMessage.success("您已同意协议");
  } catch (error) {
    ElMessage.error("操作失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 监听滚动事件
onMounted(() => {
  const content = document.querySelector(".agreement-content");
  if (content) {
    content.addEventListener("scroll", handleScroll);
  }
});
</script>

<style lang="scss" scoped>
.agreement-dialog {
  :deep(.el-overlay) {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    height: 100%;
  }

  :deep(.el-dialog) {
    @apply max-w-5xl;
    position: fixed !important;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
    margin: 0 !important;
    max-height: 80vh;
    display: flex;
    flex-direction: column;
  }

  :deep(.el-dialog__header) {
    padding: 20px 20px 0;
    margin: 0;
  }

  :deep(.el-dialog__body) {
    flex: 1;
    margin: 0;
    padding: 20px;
    overflow: hidden;
  }

  :deep(.el-dialog__footer) {
    padding: 20px;
    margin: 0;
    border-top: 1px solid #e4e7ed;
  }

  .agreement-wrapper {
    height: 100%;
    min-height: 300px;
    position: relative;

    .agreement-nav {
      background-color: #f8fafc;
      @apply dark:bg-gray-800;

      ul li {
        @apply px-3 py-2 rounded-lg transition-colors duration-200;

        &:hover {
          @apply bg-gray-100 dark:bg-gray-700;
        }

        &.active {
          @apply bg-primary-50 dark:bg-primary-900/30 text-primary-600 dark:text-primary-400;
        }
      }
    }
  }

  .agreement-content {
    height: 50vh;
    overflow-y: auto;
    padding: 0 20px;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
      background: #888;
      border-radius: 3px;

      &:hover {
        background: #555;
      }
    }
  }

  .icon-wrapper {
    @apply w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/30;
    display: flex;
    align-items: center;
    justify-content: center;

    i {
      @apply text-xl;
    }
  }
}

:deep(.agreement-modal) {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 桌面端专用类 */
.desktop-only {
  @media screen and (max-width: 768px) {
    display: none !important;
  }
}

/* 移动端样式 */
@media screen and (max-width: 768px) {
  .agreement-dialog {
    :deep(.el-dialog) {
      width: 100% !important;
      max-width: 100% !important;
      height: 100vh !important;
      max-height: 100vh !important;
      margin: 0 !important;
      border-radius: 0 !important;
      display: flex;
      flex-direction: column;
      background-color: #f8fafc;

      .el-dialog__header {
        padding: 0;
        margin: 0;
        background: #fff;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
        position: relative;
        z-index: 10;

        .dialog-header {
          padding: 1rem;
          display: flex;
          align-items: center;
          justify-content: space-between;
          border-bottom: none;

          .flex {
            display: flex;
            align-items: center;
            gap: 0.75rem;

            .icon-wrapper {
              width: 2.5rem;
              height: 2.5rem;
              background: rgba(37, 99, 235, 0.1);
              border-radius: 0.75rem;

              i {
                font-size: 1.25rem;
                color: #2563eb;
              }
            }

            div {
              h2 {
                font-size: 1.25rem;
                font-weight: 600;
                color: #1f2937;
                margin-bottom: 0.25rem;
              }

              p {
                font-size: 0.75rem;
                color: #6b7280;
              }
            }
          }
        }
      }

      .el-dialog__body {
        flex: 1;
        padding: 0;
        overflow: hidden;
        display: flex;
        flex-direction: column;
      }

      .el-dialog__footer {
        padding: 1rem;
        background: #fff;
        border-top: 1px solid #e5e7eb;
        box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.05);

        .dialog-footer {
          .flex:first-child {
            margin-bottom: 1rem;

            .el-checkbox {
              .el-checkbox__label {
                font-size: 0.875rem;
                color: #374151;
              }
            }
          }

          .flex:last-child {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0.75rem;

            .el-button {
              margin: 0;
              height: 2.75rem;
              font-size: 0.875rem;
              font-weight: 500;
              border-radius: 0.75rem;

              &:first-child {
                background: #f3f4f6;
                border-color: #e5e7eb;
                color: #374151;

                &:active {
                  background: #e5e7eb;
                }
              }

              &:last-child {
                background: #2563eb;
                border-color: #2563eb;

                &:active {
                  background: #1d4ed8;
                }

                &:disabled {
                  background: #93c5fd;
                  border-color: #93c5fd;
                }
              }
            }
          }
        }
      }
    }

    .agreement-wrapper {
      flex: 1;
      display: flex;
      flex-direction: column;
      height: auto;
      min-height: 0;
      background: #fff;

      .flex {
        flex: 1;
        display: flex;
        flex-direction: column;
        min-height: 0;

        .agreement-content {
          flex: 1;
          height: auto;
          padding: 1.25rem 1rem;
          overflow-y: auto;
          -webkit-overflow-scrolling: touch;
          background: #fff;

          &::-webkit-scrollbar {
            width: 4px;
          }

          &::-webkit-scrollbar-track {
            background: transparent;
          }

          &::-webkit-scrollbar-thumb {
            background: #d1d5db;
            border-radius: 2px;
          }

          h3 {
            font-size: 1.125rem;
            font-weight: 600;
            color: #111827;
            margin: 1.5rem 0 1rem;

            &:first-child {
              margin-top: 0;
            }
          }

          p {
            font-size: 0.9375rem;
            line-height: 1.6;
            color: #374151;
            margin-bottom: 1rem;
          }

          ul {
            margin: 1rem 0;
            padding-left: 1.25rem;

            li {
              font-size: 0.9375rem;
              line-height: 1.6;
              color: #374151;
              margin-bottom: 0.5rem;
              position: relative;

              &::before {
                content: "";
                position: absolute;
                left: -1.25rem;
                top: 0.75rem;
                width: 0.375rem;
                height: 0.375rem;
                background: #2563eb;
                border-radius: 50%;
              }
            }
          }
        }
      }
    }
  }

  :deep(.agreement-modal) {
    background: rgba(0, 0, 0, 0.3);
    backdrop-filter: blur(4px);
  }
}
</style>
